using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting.Channels;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting;
using System.Collections;
using System.Reflection;

namespace Colman.Rpg.Server
{
    /// <summary>
    /// Server Initialization
    /// </summary>
    public static class Program
    {
        static void Main(string[] args)
        {
            BinaryServerFormatterSinkProvider serverSinkProvider = new BinaryServerFormatterSinkProvider();
            serverSinkProvider.TypeFilterLevel = TypeFilterLevel.Full;

            IDictionary props = new Hashtable();
            props["port"] = 12345;

            ChannelServices.RegisterChannel(
                new TcpChannel(props, new BinaryClientFormatterSinkProvider(), serverSinkProvider),
                false);

            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(ServerEndPoint),
                "Rpg",
                WellKnownObjectMode.Singleton);

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Console.WriteLine("Server is operational. To stop, please press 'q'.");

            while (Console.ReadKey().Key != ConsoleKey.Q) ;

            Console.WriteLine();
            Console.WriteLine("Please wait while shutting down.");

            ServerEndPoint endPoint = (ServerEndPoint)Activator.GetObject(
                typeof(IServerProxy),
                "tcp://localhost:12345/Rpg");

            endPoint.Shutdown();
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            System.Diagnostics.Debugger.Break();
        }
    }
}
